package impl

import (
	"context"
	"user-server/src/boot"
	"user-server/src/model"
	"user-server/src/util/logs"
)

const (
	UserInfoPrefix = "u:"
	NickName       = "n"
	Profile        = "p"
	Password       = "d"
)

type UserCacheServiceImpl struct {
	Redis *boot.RedisEngine
}

// GetUserInfoByUserName 从缓存中获取用户信息
func (uc *UserCacheServiceImpl) GetUserInfoByUserName(ctx context.Context, username string) *model.UserInfo {
	redisKey := UserInfoPrefix + username

	result, err := uc.Redis.HGetAll(ctx, redisKey).Result()
	if err != nil {
		logs.Warn("Get UserInfo from cache fail, redisKey:", redisKey)
		return nil
	}
	if result[NickName] == "" {
		return nil
	}
	return &model.UserInfo{
		Username: username,
		Nickname: result[NickName],
		Profile:  result[Profile],
		Password: result[Password],
	}
}

//CacheUserInfoByUserName 数据库查询出来的用户信息缓存到redis
func (uc *UserCacheServiceImpl) CacheUserInfoByUserName(ctx context.Context, userInfo *model.UserInfo) {
	if userInfo != nil {
		redisKey := UserInfoPrefix + userInfo.Username

		m := map[string]string{
			NickName: userInfo.Nickname,
			Profile:  userInfo.Profile,
			Password: userInfo.Password,
		}
		uc.Redis.HMSet(ctx, redisKey, m)
	}
}

//DelUserInfoByUserName 更新用户信息之后，主动删除缓存信息
func (uc *UserCacheServiceImpl) DelUserInfoByUserName(ctx context.Context, username string) {
	redisKey := UserInfoPrefix + username
	uc.Redis.Del(ctx, redisKey)
}
